const style = require('./render/style')
const template = require('./render/template')
const dataDemo = require('./render/dataDemo')
const Layout = require('./engine').default;

let __env = GameGlobal.wx || GameGlobal.tt || GameGlobal.swan;
let sharedCanvas = __env.getSharedCanvas();
let sharedContext = sharedCanvas.getContext('2d');
let isCanClick = false;

function draw() {
  dataDemo((data, slefOpenid={}) => {
    if(!data[0]) return
    Layout.clear();
    let html = template(data, slefOpenid)
    Layout.init(html, style);
    let main = Layout.getElementsById("main")
    let shareBtns = Layout.getElementsByClassName('btnShare')
    console.log("template", shareBtns)
    // main.forEach((item)=>{
    //   item.on("touchstart",(e)=>{
    //     console.log("main",e)
    //   })
    // })
    shareBtns.forEach((item) => {
      item.on("touchend", (e) => {
        if (isCanClick) {
          if(slefOpenid.nickName!=item.children[0].idName){

            wx.shareMessageToFriend({
              openId: item.idName
            })
            console.log("btn", e, item)
          }else{
            console.warn("不能分享给自己", e, item)
          }
        }
      })
    })

    Layout.layout(sharedContext);
  })
}

function updateViewPort(data) {
  Layout.updateViewPort({
    x: data.x,
    y: data.y,
    width: data.width,
    height: data.height,
  });
}

__env.onMessage(data => {
  if (data.event == "getRank") {
    isCanClick = true
  } else if (data.event == 'hideRank') {
    isCanClick = false
  }
  if (data.type === 'engine' && data.event === 'viewport') {
    updateViewPort(data);
    draw();
  }

});